package cn.lyjuan.dwz_manage.core.java.taglibs;

import cn.lyjuan.dwz_manage.core.java.cst.TypeCst;
import org.springframework.security.taglibs.authz.AbstractAuthorizeTag;
import org.springframework.util.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.DynamicAttributes;
import javax.servlet.jsp.tagext.Tag;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by chad on 2016/9/13.
 */
public class JspElementTag extends AbstractAuthorizeTag implements Tag, DynamicAttributes
{
    private   Tag         parent;
    protected PageContext pageContext;

    /**
     * 动态属性
     */
    private Map<String, String> dynameAttrs = new HashMap<>();
    /**
     * HTML元素标签名称
     */
    private String  htmlName;
    /**
     * 请求URL地址，不带后缀，由配置决定
     */
    private String  url;
    /**
     * URL属性名称，默认为 href
     */
    private String  urlName = "href";
    /**
     * 请求参数
     */
    private String  data;
    /**
     * DWZ后台 请求标识
     */
    private String  rel;
    /**
     * 跳过权限认证
     */
    private boolean skipAuth;
    /**
     * 是否有权限
     */
    private boolean authorized;

    @Override
    public int doStartTag() throws JspException
    {
        try
        {
            this.authorized = super.authorize();

            if (this.skipAuth || this.authorized)// 有权限
            {
                StringBuilder result = new StringBuilder()
                        .append("<").append(this.htmlName).append(" ");
                if (!StringUtils.isEmpty(this.url))
                {
                    result.append(this.urlName + "=\"" + this.url);
                    if (!StringUtils.isEmpty(this.data))// 拼接参数
                        result.append("?").append(this.data);
                    result.append("\"");
                }
                if (!StringUtils.isEmpty(this.rel))// 拼接rel
                    result.append(" rel=\"").append(this.rel).append("\"");

                String key = null;// 拼接动态参数
                for (Iterator<String> it = dynameAttrs.keySet().iterator(); it.hasNext(); )
                {
                    key = it.next();
                    result.append(" ").append(key).append("=").append(dynameAttrs.get(key));
                }
                result.append(">");
                // 输出
                this.pageContext.getOut().write(result.toString());
                // 内容
                return EVAL_BODY_INCLUDE;// 计算内容
            }

            return SKIP_BODY;// 跳过内容
        } catch (IOException e)
        {
            throw new JspException(e);
        }
    }

    @Override
    public int doEndTag() throws JspException
    {
        try
        {
            if (this.skipAuth || this.authorized)// 有权限
            {
                this.pageContext.getOut().write("</" + this.htmlName + ">");
            }
        } catch (IOException e)
        {
            throw new JspException(e);
        }
        return EVAL_PAGE;
    }

    @Override
    public void setUrl(String url)
    {
        // 拼接后缀
        this.url = url = url + this.getRequest().getAttribute(TypeCst.RequestAttributes.HTTP_SUFFIX_NAME);
        // 权限验证需要URL
        if (!url.startsWith("/")) url = "/" + url;
        super.setUrl(url);
    }

    @Override
    public void release()
    {
        this.pageContext = null;
        this.parent = null;
        this.dynameAttrs = null;
    }

    @Override
    public void setParent(Tag tag)
    {
        this.parent = tag;
    }

    @Override
    public Tag getParent()
    {
        return this.parent;
    }

    public void setHtmlName(String htmlName)
    {
        this.htmlName = htmlName;
    }

    public void setUrlName(String urlName)
    {
        this.urlName = urlName;
    }

    public void setData(String data)
    {
        this.data = data;
    }

    public void setRel(String rel)
    {
        this.rel = rel;
    }

    @Override
    protected ServletRequest getRequest()
    {
        return this.pageContext.getRequest();
    }

    @Override
    protected ServletResponse getResponse()
    {
        return this.pageContext.getResponse();
    }

    @Override
    protected ServletContext getServletContext()
    {
        return this.pageContext.getServletContext();
    }

    public void setSkipAuth(boolean skipAuth)
    {
        this.skipAuth = skipAuth;
    }

    public void setPageContext(PageContext pageContext)
    {
        this.pageContext = pageContext;
    }

    @Override
    public void setDynamicAttribute(String uri, String key, Object val) throws JspException
    {
        dynameAttrs.put(key, (String) val);
    }
}
